
// Open MoneySpinner Suite v1
// An open source business management software system written in Java and MySQL
// Recommended IDE is NetBeans IDE 7.0.1
// Support Web Site: http://www.milliscript.com
//
// Copyright (C) 2014, Abiodun Aremu, Ibadan/NIGERIA.
// Open MoneySpinner Suite is distributed under the terms of the Apache License version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*
 * BackupDatabase.java
 *
 * Created on Jan 27, 2011, 11:36:23 PM
 */

package openmoneyspinnersuite;

/**
 *
 * @author Abiodun Aremu
 */
import javax.swing.*;
import java.sql.*;

final class BackupDatabase extends javax.swing.JInternalFrame {
PreparedStatement statement;
Thread backupDatabaseThread=new Thread();
Thread backupDatabaseTitleThread=new Thread();
    /** Creates new form TransactionType */
     BackupDatabase() {
        initComponents();
        jBackupTypeComboBox.setSelectedItem("FULL");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jDatabaseBackupButton = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jBackupTypeComboBox = new javax.swing.JComboBox();

        setClosable(true);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(openmoneyspinnersuite.OpenMS_Finance_App.class).getContext().getResourceMap(BackupDatabase.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setFrameIcon(resourceMap.getIcon("Form.frameIcon")); // NOI18N
        setName("Form"); // NOI18N
        setVisible(true);

        jPanel1.setName("jPanel1"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jDatabaseBackupButton.setFont(resourceMap.getFont("jDatabaseBackupButton.font")); // NOI18N
        jDatabaseBackupButton.setIcon(resourceMap.getIcon("jDatabaseBackupButton.icon")); // NOI18N
        jDatabaseBackupButton.setText(resourceMap.getString("jDatabaseBackupButton.text")); // NOI18N
        jDatabaseBackupButton.setName("jDatabaseBackupButton"); // NOI18N
        jDatabaseBackupButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jDatabaseBackupButtonActionPerformed(evt);
            }
        });

        jButton1.setFont(resourceMap.getFont("jButton1.font")); // NOI18N
        jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jBackupTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-- Select --", "TRANSACTION LOG", "DIFFERENTIAL", "FULL" }));
        jBackupTypeComboBox.setEnabled(false);
        jBackupTypeComboBox.setName("jBackupTypeComboBox"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBackupTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jDatabaseBackupButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jBackupTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 65, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jDatabaseBackupButton, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jDatabaseBackupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jDatabaseBackupButtonActionPerformed
        // TODO add your handling code here:
        if(jBackupTypeComboBox.getSelectedItem().toString().trim().equals("-- Select --"))
        {
            JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),"Please Select a Backup Type ","ERROR !",JOptionPane.ERROR_MESSAGE);
            return;
        }
        else
        {
            /* Execute submit thread */
            backupDatabaseThread=new Thread(new Runnable() {
                public void run() {
                    disableControls();
                    submitData();
                    reset();
                }
            });
            backupDatabaseTitleThread=new Thread(new Runnable() {
                public void run() {
                    while(backupDatabaseThread.isAlive())setProcessingTitle(backupDatabaseTitleThread);
                    enableControls();
                    System.out.println("databaseBackupThread stopped runing.");
                }
            });
            backupDatabaseThread.start();
            backupDatabaseTitleThread.start();
        }
    }//GEN-LAST:event_jDatabaseBackupButtonActionPerformed
                                
    private void setProcessingTitle(Thread thread)
    {
        try{
            this.setTitle("::. New Database Backup - Processing Request");
            thread.sleep(500);
            this.setTitle("::. New Database Backup - Processing Request.");
            thread.sleep(500);
            this.setTitle("::. New Database Backup - Processing Request..");
            thread.sleep(500);
            this.setTitle("::. New Database Backup - Processing Request...");
            thread.sleep(500);
        }catch(Exception e){System.out.println("Title thread"+e);}
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        if(backupDatabaseThread.isAlive())
        {
            try{
                backupDatabaseThread.stop();
                backupDatabaseTitleThread.stop();
                System.out.println("Threads successfully stopped.");
            }catch(Exception e){System.out.println("Thread stopping error: "+e);}
            this.setTitle("::. New Database Backup");
            enableControls();
        }
        else
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

     void reset()
    {
        //jBackupTypeComboBox.setSelectedItem("-- Select --");
    }
     void disableControls()
     {
         jDatabaseBackupButton.setEnabled(false);
     }
     void enableControls()
     {
         jDatabaseBackupButton.setEnabled(true);
     }
     void submitData()
    {
        java.lang.Runtime run=java.lang.Runtime.getRuntime();
            
        ConnectUnsafe.createMSSQLConnection();
        ConnectUnsafe.changeDB(OpenMSApp.Database_A);
        statement=ConnectUnsafe.createStatement(ConnectUnsafe.procInit+" prnInsBackupRecord"+Connect.procInitStart+"?,?,?"+Connect.procInitEnd);
            try{
       
//            java.util.Date date=java.util.Calendar.getInstance().getTime();
            String d="";//String.valueOf(date);
            String ed[]=new String[2];
            String ad[]=new String[2];
            ed[0]="CLASSPATH=C:\\Program Files\\Milliscript IT Enterprises\\Database\\MySQL Server 6.0\\bin\\";
            ed[1]="Path=C:\\Program Files\\Milliscript IT Enterprises\\Database\\MySQL Server 6.0\\bin\\";
            ad[0]="C:\\Program Files\\Milliscript IT Enterprises\\Database\\MySQL Server 6.0\\bin\\mysqldump";
            ad[1]=" --all-databases -u root --password=milli 1> \"c:\\Program Files\\Milliscript IT Enterprises\\okk.mis\"";
           // ad[2]="-u";
//            ad[3]="root";
//            ad[4]="--password=milli";
//            ad[5]="1>";
//            ad[6]="c:\\Program Files\\Milliscript IT Enterprises\\okk.mis";
//            d=d.replace(" ", "_");
//            d=d.replace(":", "_");
            d=Configuration.backupDirPath+"OK1.mis";
//           // System.out.println(d);
            //System.out.println("C:\\Program Files\\Milliscript IT Enterprises\\Database\\MySQL Server 6.0\\bin\\mysqldump --all-databases -u root --password=milli 1>"+d+"");
            System.out.println("\"C:\\Program Files\\Milliscript IT Enterprises\\Database\\MySQL Server 6.0\\bin\\mysqldump\" --all-databases -u root --password=milli 1> \"c:\\Program Files\\Milliscript IT Enterprises\\okk.mis\"");
                        //run.exec("mysqldump --all-databases -u root --password=milli 1> \"c:\\Program Files\\Milliscript IT Enterprises\\okk.mis\"",ed);
                        run.exec("C:\\Program Files\\Milliscript IT Enterprises\\Database\\MySQL Server 6.0\\bin\\mysqldump");
                        //run.exec("mysqldump milliscriptmoneyspinnerasxtrial -u root --password=milli 1>"+d+"");
////            run.exec(Configuration.backupDirPath+"\\ok.bat");
//        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(milliscriptdms.OpenMSApp.class).getContext().getResourceMap(BackupDatabase.class);
//        String dir=resourceMap.getResourcesDir()+"ok.bat";
//        java.io.File f=new java.io.File(dir+"ok.bat");
//        java.net.URL url = resourceMap.getClassLoader().getResource(dir);

//        System.out.println(url);
            String filePath="C:\\Milliscript_MoneySpinner\\ok.bat";
            NoteWriter note=new NoteWriter();
            note.writeMyBackup(filePath);
            try
            {
                run.exec(filePath);
                java.io.File file=new java.io.File(filePath);

                if(file.exists())
                {
                    System.out.println("bat file still available");
                    file.delete();
                }
            }
            catch(Exception e){System.out.println("Error occured while deleting file "+e);}
            
                statement.setString(1,jBackupTypeComboBox.getSelectedItem().toString().trim());
                statement.setString(2,OpenMSApp.LoginCode);
                statement.setString(3,OpenMSApp.Database_A);
            
                ConnectUnsafe.executeUpdateStatement(statement);
                ConnectUnsafe.closeConnection();
                System.out.println("Backup submitted");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox jBackupTypeComboBox;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jDatabaseBackupButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables

}
